package com.lk.pet.vet.service;


import com.lk.pet.vet.model.Specialty;
import com.lk.pet.vet.model.Vet;
import com.lk.pet.vet.model.VetLog;
import com.lk.pet.vet.repos.SpecialtyRepository;
import com.lk.pet.vet.repos.VetLogRepository;
import com.lk.pet.vet.repos.VetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class VetService {

    @Autowired
    SpecialtyRepository specialtyRepository;
    @Autowired
    VetRepository vetRepository;
    @Autowired
    VetLogRepository vetLogRepository;

    public Vet add(Vet vet){
        return vetRepository.save(vet);
    }

    public Optional<Vet> getVet(Integer id) {
        return vetRepository.findById(id);
    }

    public List<Vet> getVets(){
        return vetRepository.findAll();
    }
    public Specialty getSpecialty(int id){
        return specialtyRepository.getById(id);
    }
    public void delVet(int id){
        vetRepository.deleteById(id);
    }

    public Specialty add(String name){
        Specialty specialty = new Specialty();
        specialty.setName(name);
        return specialtyRepository.save(specialty);
    }

    public List<Specialty> findAllSpecialties(){
        return specialtyRepository.findAll();
    }

    public void update(Specialty specialty){
        specialtyRepository.save(specialty);
    }

    public void addSpecialtyToVet(int vetId, int specialtyId){
        Vet vet = vetRepository.getById(vetId);
        Specialty specialty = specialtyRepository.getById(specialtyId);
        vet.getSpecialties().add(specialty);
        vetRepository.save(vet);
    }

    public void removeSpecialtyFromVet(int vetId, int specialtyId){
        Vet vet = vetRepository.getById(vetId);
        Specialty specialty = specialtyRepository.getById(specialtyId);
        vet.getSpecialties().remove(specialty);
        vetRepository.save(vet);
    }

    public void delSpecialty(Integer id){
        specialtyRepository.deleteById(id);
    }

    public VetLog log(Integer vetId, @Nullable String note){
        Vet vet = vetRepository.getById(vetId);
        VetLog vlog = new VetLog();
        vlog.setNote(note);
        vlog.setVet(vet);
        vlog.setCreateTime(new Date());
        vlog = vetLogRepository.save(vlog);
        return vlog;
    }

    public Page<VetLog> queryLog(Pageable pageable){
        return vetLogRepository.findAll(pageable);
    }
}
